<style>
    /* 整体布局 */
    body {
        font-family: 'Segoe UI', Arial, sans-serif;
        max-width: 800px;
        margin: 20px auto;
        padding: 20px;
        background-color: #f5f5f5;
    }

    /* 输入区域 */
    .input-group {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
    }

    input[type="text"] {
        flex: 1;
        padding: 12px;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        font-size: 14px;
        transition: border-color 0.3s;
    }

    input[type="text"]:focus {
        border-color: #2196F3;
        outline: none;
    }

    /* 按钮样式 */
    button {
        padding: 12px 24px;
        background-color: #2196F3;
        color: white;
        border: none;
        border-radius: 8px;
        cursor: pointer;
        transition: background 0.3s, transform 0.2s;
    }

    button:hover {
        background-color: #1976D2;
        transform: translateY(-1px);
    }

    button:active {
        transform: translateY(0);
    }

    /* 消息容器 */
    #messages {
        background: white;
        border-radius: 12px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        padding: 20px;
        min-height: 400px;
        max-height: 60vh;
        overflow-y: auto;
    }

    /* 消息气泡 */
    .message {
        margin: 12px 0;
        padding: 12px 16px;
        border-radius: 8px;
        background: #f8f9fa;
        max-width: 80%;
        animation: fadeIn 0.3s ease;
    }

    /* 系统消息 */
    .system-message {
        background: #e3f2fd;
        color: #1976D2;
        text-align: center;
        margin: 20px auto;
    }

    /* 用户消息 */
    .user-message {
        background: #2196F3;
        color: white;
        margin-left: auto;
    }

    /* 时间戳 */
    .timestamp {
        font-size: 0.8em;
        color: #757575;
        margin-top: 4px;
    }

    /* 滚动条美化 */
    ::-webkit-scrollbar {
        width: 8px;
    }

    ::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    ::-webkit-scrollbar-thumb {
        background: #bdbdbd;
        border-radius: 4px;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }

    /* 响应式设计 */
    @media (max-width: 600px) {
        .input-group {
            flex-direction: column;
        }

        button {
            width: 100%;
        }
    }
</style>

<!-- 修改后的HTML结构 -->
<div class="container">
    <div class="input-group">
        <input type="text" id="roomKey" placeholder="聊天室名称">
        <input type="text" id="userName" placeholder="用户名">
        <button onclick="connect()">加入聊天室</button>
        <button onclick="loginOut()">离开聊天室</button>
    </div>

    <div id="messages"></div>

    <div class="input-group" style="margin-top: 20px;">
        <input type="text" id="msgInput" placeholder="输入消息...">
        <button onclick="send()">发送</button>
    </div>
</div>


<script>
    let ws = null;
    let currentKey = "";
    let currentName = "";

    // 连接聊天室
    function connect() {
        const chatName = document.getElementById("roomKey").value;
        const senderName = document.getElementById("userName").value;

        // 双重非空校验
        if (!chatName.trim() || !senderName.trim()) {
            alert("聊天室名称和用户名不能为空！");
            return;
        }
        // 关闭旧连接
        if (ws) ws.close();

        currentKey = chatName;
        currentName = senderName;

        // 携带两个参数：路径参数key + 查询参数name
        ws = new WebSocket(`ws://localhost:8080/chat/${encodeURIComponent(chatName)}/${encodeURIComponent(senderName)}`);

        ws.onopen = () => {
            console.log("已加入聊天室:", currentKey);
            // 发送初始化消息（可选）
            ws.send(JSON.stringify({
                type: "init",
                chatName: currentKey,
                senderName: currentName
            }));
        };

        ws.onmessage = (event) => {
            const data = JSON.parse(event.data);
            console.log(event.data);
            const messagesContainer = document.getElementById("messages");

            // 新增历史消息处理逻辑
            if (Array.isArray(data)) {  // 判断是否为历史消息数组
                data.forEach(msg => {
                    console.log(msg)
                    const msgElement = createMessageElement(msg);
                    console.log(msgElement)
                    messagesContainer.appendChild(msgElement);
                });
            } else {  // 处理实时消息
                const msgElement = createMessageElement(data);
                messagesContainer.appendChild(msgElement);
            }
        };

        ws.onerror = (error) => {
            console.error("连接错误:", error);
        };
    }

    //发送消息
    function send() {
        if (!ws || ws.readyState !== WebSocket.OPEN) {
            alert("请先建立连接！");
            return;
        }
        const msg = document.getElementById("msgInput").value;
        ws.send(JSON.stringify({
            type: "message",
            chatName: currentKey,
            senderName: currentName,
            content: msg
        }));
        document.getElementById("msgInput").value = ""; // 清空输入框
    }

    //断开连接
    // 修改 loginOut 函数，增加系统消息广播
    function loginOut() {
        if (ws && ws.readyState === WebSocket.OPEN) {
            // 立即在本地生成退出提示
            const messagesContainer = document.getElementById("messages");
            const msgElement = createMessageElement({
                type: "logout",
                senderName: currentName
            });
            messagesContainer.appendChild(msgElement);

            // 关闭连接并清空数据
            ws.close();
            currentKey = "";
            currentName = "";
            document.getElementById("msgInput").value = "";
            document.getElementById("roomKey").value = "";
            document.getElementById("userName").value = "";
        }
    }

    // 新增通用消息创建函数
    function createMessageElement(msg) {
        const msgElement = document.createElement("div");
        msgElement.className = "message"; // 基础样式

        let content = '';
        let extraClass = '';
        let timestamp = '';

        switch(msg.type) {
            case "init":
                content = `[系统] ${msg.senderName} 加入了聊天室`;
                extraClass = "system-message";
                break;
            case "message":
                content = `${msg.senderName} : ${msg.content}`;
                extraClass = "user-message";
                break;
            case "history":
                content = `${msg.senderName}: ${msg.content}`;
                timestamp = `<div class="timestamp">${formatTime(msg.createdAt)}</div>`;
                break;
            case "logout":  // 新增退出类型处理
                content = `[系统] ${msg.senderName} 退出了聊天室`;
                extraClass = "system-message";
                break;
            case "error":
                content = `[系统] ${msg.content} `
                extraClass = "system-message";
                break
        }

        msgElement.innerHTML = `${content}${timestamp}`;
        if(extraClass) msgElement.classList.add(extraClass);
        return msgElement;
    }

    // 新增时间格式化函数
    function formatTime(timestamp) {
        const date = new Date(timestamp);
        // 示例格式：2025-03-19 15:04
        return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
    }

    // 补零函数
    function pad(num) {
        return num.toString().padStart(2, '0');
    }
</script>